﻿using JWT;
using JWT.Algorithms;
using JWT.Exceptions;
using JWT.Serializers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Web;

namespace ProjectManage.Common
{

    public class JwtTools
    {
        static IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); // 加密算法，使用256算法进行加密
        static IJsonSerializer serializer = new JsonNetSerializer(); // 加密器，进行序列化
        static IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); // base64加密，转义（好像）
        static IDateTimeProvider provider = new UtcDateTimeProvider();
        static string secret = "JGmgsystemJD&djc12.$2#}s";

        public static string CreateJWT(Dictionary<string, object> payload)
        {
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            return encoder.Encode(payload, secret);
        }

        public static string ValidateJWT(string token)
        {
            try
            {
                IJwtValidator validator = new JwtValidator(serializer, provider);//用于验证JWT的类
                                                                                 //  IJwtAlgorithm algorithm= new HMACSHA256Algorithm();
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);//用于解析JWT的类
                //var token = headers.GetValues("token").First();
                string payload = decoder.Decode(token, secret, verify: true);
                return payload;
            }
            catch (TokenExpiredException)//当前时间大于负载过期时间（负荷中的exp），会引发Token过期异常
            {
                return "过期";
            }
            catch (SignatureVerificationException)//如果签名不匹配，引发签名验证异常
            {
                return "签名异常";
            }
        }

    }
}